package net.libra.loader
{
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Dictionary;
	
	/**
	 * 并发加载
	 * IE下最多运行2并发，而且并发，数据量过大的时候容易卡死
	 * @author elvisjiang
	 */
	public class SwfLoader2 extends EventDispatcher
	{
		public static var MAX_NUM:int = 30;//并发数
		private var _paths:Array = [];
		private var _dict:Dictionary = new Dictionary();
		
		public function SwfLoader2():void
		{
			for(var i:int = 0;i<MAX_NUM;i++)
			{
				var loader:Loader = new Loader();
				_dict[loader] = {busy:false,url:""};
				var context:LoaderContext = new LoaderContext(false,ApplicationDomain.currentDomain);
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,__onResult);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,__onResult);
				loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,__onResult);
				
//				loader.load(new URLRequest(url + "?vesion = "+GameLib.gameVesion),context);
			}
		}
		public function addURLArray(arry:Array):void
		{
			_paths = arry;
			_totalLoadedNum = _paths.length;
		}
		public function start():void
		{
			while (true)
			{
				if(_paths.length <= 0) break;
				
				var url:String = _paths.shift();
				var loader:Loader = getLoader();
				loader.load(new URLRequest(url));
				_dict[loader].busy = true;
				_dict[loader].url = url;
				
			}
		}
		public function getLoader():Loader
		{
			var result:Loader;
			for (var loader:Object in _dict)
			{
				if(!_dict[loader].busy)
				{
					result = loader as Loader;
					break;
				}
			}
			if(result == null)
			{
				throw new Error("目前都在忙...请稍等...");
			}
			return result;
		}
		private var _loadedNum:int = 0;
		private var _totalLoadedNum:int = 0;
		protected function __onResult(event:Event):void
		{
			var contentLoaderInfo:LoaderInfo = event.target as LoaderInfo;
			if(event.type == IOErrorEvent.IO_ERROR)
			{
				throw new Error("路径有错，检查下URL");
				Log.error("[SwfLoader] 路径有错，检查下URL");
			}else if(event.type == Event.COMPLETE )
			{
				for (var loader:Object in _dict)
				{
					if(loader.contentLoaderInfo == contentLoaderInfo)
					{
						trace("[SwfLoader] Loaded " + _dict[loader].url + "加载完毕!");
						_dict[loader].busy = false;
						_dict[loader].url = "";
					}
				}
				_loadedNum ++;
				if(_loadedNum == _totalLoadedNum)
				{
					trace("[SwfLoader] AllItemsLoaded");
					this.dispatchEvent(new LoaderEvent(LoaderEvent.ON_COMPLETE));
				}
			}
		}
		
	}
}